import pymysql
import traceback # 可以将报错信息打印在控制台上面

class DB:
    def __init__(self,user,password,host,database):
        self.user = user
        self.password = password
        self.host = host
        self.database = database
    def connect(self):
        # 创建数据库对象
        self.db = pymysql.connect(user = self.user,password= self.password,host=self.host,database=self.database,cursorclass =
        pymysql.cursors.DictCursor)
        # 通过数据库对象创建游标
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def search(self,type:int,sql):
        """
        :param type: 1 找到符合一条的数据  2 找到符合的全部数据
        :return:
        """
        # 先去调用连接数据库的方法
        self.connect()
        result = None
        if type == 1:
            try:
                self.cursor.execute(sql)
                result = self.cursor.fetchone()
                self.close()
                return result
            except:
                self.db.rollback() # 如果出现了异常，就回滚操作
                traceback.print_exc()
                return result
        elif type == 2:
            try:
                self.cursor.execute(sql)
                result = self.cursor.fetchall()
                self.close()
                return result
            except:
                self.db.rollback() # 如果出现了异常，就回滚操作
                traceback.print_exc()
                return result
    def __edit(self,sql):
        self.connect()
        try:
            self.cursor.execute(sql)
            self.db.commit()
            self.close()
        except:
            self.db.rollback()
            traceback.print_exc()
    def insert(self,sql): # 新增
        self.__edit(sql)
    def delete(self,sql): # 删除
        self.__edit(sql)
    def update(self,sql): # 更新
        self.__edit(sql)
if __name__ == '__main__':
    # 创建d1对象
    d1 = DB(user='root',password='123456',host='8.148.229.201',database='jiac')
    # 查询
    # print(d1.search(2, "select * from student"))
    # 新增
    # d1.insert("insert into student(name,phone,address) values('李四','123','辽宁锦州')")
    # 查询
    # print(d1.search(1,"select * from student where name='李四'"))
    # 删除
    # d1.delete("delete from student where id=7")

    # 更新操作
    d1.update("update student set name='张鑫plus' where name='张鑫'")
    # 查询
    print(d1.search(2, "select * from student"))


























